package com.xuanyuanxinyu.func.gilde;

import android.graphics.Picture;
import android.graphics.Rect;
import android.graphics.drawable.PictureDrawable;

public class PictureDrawableUtils {

    public static final float MAX_SCALE_FACTOR = 1.0f;

    private final Rect mTmpRect = new Rect();

    PictureDrawable pictureDrawableFromPicture(Picture picture) {
        PictureDrawable drawable = new PictureDrawable(picture);
        drawable.setBounds(0, 0, picture.getWidth(), picture.getHeight());
        return drawable;
    }

    // 计算图片的缩放比例
    float getScaleFactor(int srcWidth, int srcHeight, int targetWidth, int targetHeight) {
        return Math.min(MAX_SCALE_FACTOR, Math.min((float) targetWidth / (float) srcWidth,
                (float) targetHeight / (float) srcHeight));
    }

    // 计算图片的目标矩形区域
    Rect computeTargetRect(int srcWidth, int srcHeight, int targetWidth, int targetHeight) {
        float scaleFactor = getScaleFactor(srcWidth, srcHeight, targetWidth, targetHeight);
        int scaledWidth = (int) (scaleFactor * srcWidth);
        int scaledHeight = (int) (scaleFactor * srcHeight);
        int left = (targetWidth - scaledWidth) / 2;
        int top = (targetHeight - scaledHeight) / 2;
        mTmpRect.set(left, top, left + scaledWidth, top + scaledHeight);
        return mTmpRect;
    }
}
